import T from 'ant-design-vue/es/table/Table'
import get from 'lodash.get'
export default {
  data() {
    return {
      needTotalList: [],

      selectedRows: [],
      selectedRowKeys: [],

      localLoading: false,
      localDataSource: [],
      localPagination: Object.assign({}, T.props.pagination),

      filterShow: false,
    }
  },
  props: Object.assign({}, T.props, {
    rowKey: {
      type: [String, Function],
      default: 'id',
    },
    data: {
      type: Function,
      required: true,
    },
    pageNum: {
      type: Number,
      default: 1,
    },
    pageSize: {
      type: Number,
      default: 10,
    },
    showSizeChanger: {
      type: Boolean,
      default: true,
    },
    showAlertInfo: {
      type: Boolean,
      default: false,
    },
    showPagination: {
      default: 'auto',
    },
  }),
  watch: {
    'localPagination.current'(val) {
      this.$router.push({
        name: this.$route.name,
        params: Object.assign({}, this.$route.params, {
          pageNum: val,
        }),
      })
    },
    pageNum(val) {
      Object.assign(this.localPagination, {
        current: val,
      })
    },
    pageSize(val) {
      console.log('pageSize:', val)
      Object.assign(this.localPagination, {
        pageSize: val,
      })
    },
    showSizeChanger(val) {
      console.log('showSizeChanger', val)
      Object.assign(this.localPagination, {
        showSizeChanger: val,
      })
    },
  },
  created() {
    this.localPagination =
      ['auto', true].includes(this.showPagination) &&
      Object.assign({}, this.localPagination, {
        current: this.pageNum,
        pageSize: this.pageSize,
        showSizeChanger: this.showSizeChanger,
      })
    this.needTotalList = this.initTotalList(this.columns)
    this.loadData()
  },
  methods: {
    // 处理最大显示长度后的列
    allColumns() {
      let results = []
      // 设置 scroll 属性后，需要设置所有列的 width 来避免表头和内容的错位。
      // 对未设置 width 的 col 设置平均宽度
      const fullWidth = this.localScroll.x || (this.$el || {}).offsetWidth - 85
      const remainWidth = this.columns.reduce(
        (remain, { width }) =>
          width
            ? typeof width === 'string' && width.endsWith('%')
              ? remain - (parseFloat(width) * fullWidth) / 100
              : remain - parseFloat(width)
            : remain,
        fullWidth
      )
      const noWidthColCount = this.columns.reduce((count, { width }) => (width ? count : count + 1), 0)
      const averageWidth = remainWidth / noWidthColCount
      this.columns.forEach((col) => !col.width && Vue.set(col, 'width', averageWidth))

      results = this.columns.reduce((results, col) => {
        // 超出后显示省略号
        if (this.isDrag || col.key !== 'action') {
          // 组件不支持排序省略一起使用，使用排序后，表头省略会失效
          col.ellipsis = true
        }
        const result = Object.assign({}, col)
        results.push(result)
        return results
      }, results)

      return results
    },
    /**
     * 表格重新加载方法
     * 如果参数为 true, 则强制刷新到第一页
     * @param {boolean} bool
     */
    refresh(bool = false, isSearch = true) {
      !isSearch && this.resetColumns()
      bool &&
        (this.localPagination = Object.assign(
          {},
          {
            current: 1,
            pageSize: this.pageSize,
          }
        ))
      this.loadData()
    },
    /**
     * 表格列重置，主要使用在数据使用数据数组的表格
     */
    resetColumns() {
      this.filterValue = this.allColumns.map((col) => col.dataIndex || col.key || col.title)
      this.filterShow = !this.filterShow
    },
    loadData(pagination, filters, sorter) {
      this.localLoading = true
      var result = this.data(
        Object.assign(
          {
            pageNum: (pagination && pagination?.current) || this.localPagination?.current || 1,
            pageSize: (pagination && pagination.size) || this.localPagination.pageSize || 10,
          },
          (sorter &&
            sorter.field && {
              sortField: sorter.field,
            }) ||
            {},
          (sorter &&
            sorter.order && {
              sortOrder: sorter.order,
            }) ||
            {},
          {
            ...filters,
          }
        )
      )
      if (result instanceof Promise) {
        result.then((r) => {
          this.localPagination = Object.assign({}, this.localPagination, {
            current: r?.current, // 返回结果中的当前分页数
            total: r?.total, // 返回结果中的总记录数
            showSizeChanger: this.showSizeChanger,
            pageSize: (pagination && pagination.pageSize) || this.localPagination.pageSize,
          })
          //update--begin--autor:wangshuai-----date:20200724------for：判断showPagination是否为false------
          ;(!this.showPagination || (!r?.total && this.showPagination === 'auto')) && (this.localPagination = false)
          //update--end--autor:wangshuai-----date:20200724------for：判断showPagination是否为false-----
          this.localDataSource = r?.records // 返回结果中的数组数据
          this.localLoading = false
        })
      }
    },
    initTotalList(columns) {
      const totalList = []
      columns &&
        columns instanceof Array &&
        columns.forEach((column) => {
          if (column.needTotal) {
            // 是否需要统计
            totalList.push({ ...column, total: 0 })
          }
        })
      return totalList
    },
    updateSelect(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      let list = this.needTotalList
      this.needTotalList = list.map((item) => {
        return {
          ...item,
          total: selectedRows.reduce((sum, val) => {
            let total = sum + get(val, item.dataIndex)
            return isNaN(total) ? 0 : total
          }, 0),
        }
      })
      // this.$emit('change', selectedRowKeys, selectedRows)
    },
    updateEdit() {
      this.selectedRows = []
    },
    onClearSelected() {
      // 【TESTA-262】页面清空后还能才做所选行，增加  this.$emit('clearAll')
      this.selectedRowKeys = []
      this.selectedRows = []
      this.updateSelect([], [])
      this.$emit('clearAll')
    },
    renderMsg(h) {
      const _vm = this
      let d = []
      // 构建 已选择
      d.push(
        h(
          'span',
          {
            style: {
              marginRight: '12px',
            },
          },
          [
            '已选择 ',
            h(
              'a',
              {
                style: {
                  fontWeight: 600,
                },
              },
              this.selectedRows.length
            ),
          ]
        )
      )

      // 构建 列统计
      this.needTotalList.map((item) => {
        d.push(
          h(
            'span',
            {
              style: {
                marginRight: '12px',
              },
            },
            [
              `${item.title}总计 `,
              h(
                'a',
                {
                  style: {
                    fontWeight: 600,
                  },
                },
                `${!item.customRender ? item.total : item.customRender(item.total)}`
              ),
            ]
          )
        )
      })

      // 构建 清空选择
      d.push(
        h(
          'a',
          {
            style: {
              marginLeft: '24px',
            },
            on: {
              click: _vm.onClearSelected,
            },
          },
          '清空'
        )
      )

      return d
    },
    renderAlert(h) {
      return h(
        'span',
        {
          slot: 'message',
        },
        this.renderMsg(h)
      )
    },
    /**
     * 表格查询方法
     * 如果参数为 true, 则强制刷新到第一页
     * @param {boolean} bool
     */
    search() {
      this.loadData()
    },
  },

  render(h) {
    const _vm = this

    let props = {},
      localKeys = Object.keys(this.$data)

    Object.keys(T.props).forEach((k) => {
      let localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
      if (localKeys.includes(localKey)) {
        return (props[k] = _vm[localKey])
      }
      return (props[k] = _vm[k])
    })

    // 显示信息提示
    if (this.showAlertInfo) {
      props.rowSelection = {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          _vm.updateSelect(selectedRowKeys, selectedRows)
          _vm.$emit('onSelect', { selectedRowKeys: selectedRowKeys, selectedRows: selectedRows })
        },
      }

      return h('div', {}, [
        h(
          'a-alert',
          {
            style: {
              marginBottom: '16px',
            },
            props: {
              type: 'info',
              showIcon: true,
            },
          },
          [_vm.renderAlert(h)]
        ),
        h(
          'a-table',
          {
            tag: 'component',
            attrs: props,
            on: {
              change: _vm.loadData,
            },
            scopedSlots: this.$scopedSlots,
          },
          this.$slots.default
        ),
      ])
    }

    return h(
      'a-table',
      {
        tag: 'component',
        attrs: props,
        on: {
          change: _vm.loadData,
        },
        scopedSlots: this.$scopedSlots,
      },
      this.$slots.default
    )
  },
}
